package com.sxf.djiuav;

import android.app.Application;
import android.content.Context;
import android.util.Log;
import androidx.annotation.Nullable;

import dji.sdk.keyvalue.key.BatteryKey;
import dji.sdk.keyvalue.key.FlightControllerKey;
import dji.sdk.keyvalue.key.KeyTools;
import dji.sdk.keyvalue.key.ProductKey;
import dji.sdk.keyvalue.value.common.Attitude;
import dji.sdk.keyvalue.value.common.Velocity3D;
import dji.sdk.keyvalue.value.product.ProductType;
import dji.v5.common.callback.CommonCallbacks;
import dji.v5.common.error.IDJIError;
import dji.v5.common.register.DJISDKInitEvent;
import dji.v5.common.register.PackageProductCategory;
import dji.v5.manager.KeyManager;
import dji.v5.manager.SDKManager;
import dji.v5.manager.diagnostic.DJIDeviceStatus;
import dji.v5.manager.diagnostic.DJIDeviceStatusChangeListener;
import dji.v5.manager.interfaces.SDKManagerCallback;
import dji.v5.network.DJINetworkManager;
import dji.v5.utils.common.ContextUtil;

/**
 * DJI 应用类
 * 负责全局的 SDK 初始化和生命周期管理
 * 合并了 DJISDKManagement 的功能
 */
public class DJIApplication extends Application {
    private static final String TAG = "DJIApplication";

    private static DJIApplication instance;
    private boolean isSDKInitialized = false;
    private boolean isSDKRegistered = false;

    public void addLog(String s) {

    }

    // SDK 初始化监听器接口
    public interface SDKInitListener {
        void onInitSuccess();
        void onInitFailure(String error);
        void onDeviceConnected(ProductType productType);
        void onDeviceDisconnected();
        void onDeviceChanged(ProductType oldType, ProductType newType);
        void onDeviceStatusUpdated(DJIDeviceStatus from, DJIDeviceStatus to);
        void onDatabaseDownloadProgress(long current, long total);
    }

    private SDKInitListener sdkInitListener;
    private SDKManagerCallback sdkManagerCallback;
    private DJIDeviceStatusChangeListener deviceStatusChangeListener;

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        // 在调用install前，请勿调用任何MSDK相关
        // MSDK v5.10.0 之前的版本请使用 com.secneo.sdk.Helper.install(this)
        com.cySdkyc.clx.Helper.install(this);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;

        // 初始化上下文工具
        ContextUtil.init(this);

        // 初始化 SDK
        initSDKManager();
    }

    /**
     * 获取应用实例
     */
    public static DJIApplication getInstance() {
        return instance;
    }

    /**
     * 初始化 SDK 管理器
     */
    private void initSDKManager() {
        // 初始化回调
        initCallbacks();

        try {
            SDKManager.getInstance().init(this, sdkManagerCallback);
            isSDKInitialized = true;

            Log.d(TAG, "SDK初始化开始");
        } catch (Exception e) {
            Log.e(TAG, "SDK初始化异常: " + e.getMessage());
            if (sdkInitListener != null) {
                sdkInitListener.onInitFailure(e.getMessage());
            }
        }
    }

    /**
     * 初始化回调
     */
    private void initCallbacks() {
        // SDK管理器回调
        sdkManagerCallback = new SDKManagerCallback() {
            @Override
            public void onInitProcess(DJISDKInitEvent event, int totalProcess) {
                Log.d(TAG, "SDK初始化进度: " + event.name() + ", 总进度: " + totalProcess);

                if (sdkInitListener != null) {
                    sdkInitListener.onDatabaseDownloadProgress(totalProcess, 100); // 示例进度
                }

                // 当初始化完成时，注册应用
                if (event == DJISDKInitEvent.INITIALIZE_COMPLETE) {
                    isSDKInitialized = true;
                    registerApp();
                }
            }

            @Override
            public void onRegisterSuccess() {
                Log.d(TAG, "SDK注册成功");
                isSDKRegistered = true;
                if (sdkInitListener != null) {
                    sdkInitListener.onInitSuccess();
                }
            }

            @Override
            public void onRegisterFailure(IDJIError error) {
                Log.e(TAG, "SDK注册失败: " + error.description());
                isSDKRegistered = false;
                if (sdkInitListener != null) {
                    sdkInitListener.onInitFailure(error.description());
                }
            }

            public void onProductChange(Object oldProduct, Object newProduct) {
                ProductType oldType = getProductType();
                ProductType newType = getProductType();

                Log.d(TAG, "产品类型变更: " +
                        (oldType != null ? oldType.name() : "无") +
                        " -> " +
                        (newType != null ? newType.name() : "无"));

                if (sdkInitListener != null) {
                    sdkInitListener.onDeviceChanged(oldType, newType);
                }
            }

            @Override
            public void onProductDisconnect(int productId) {
                Log.d(TAG, "产品断开连接, ID: " + productId);
                if (sdkInitListener != null) {
                    sdkInitListener.onDeviceDisconnected();
                }
            }

            @Override
            public void onProductConnect(int productId) {
                Log.d(TAG, "产品连接, ID: " + productId);
                // 获取连接的产品类型
                ProductType productType = getProductType();

                if (sdkInitListener != null) {
                    sdkInitListener.onDeviceConnected(productType);
                }
            }

            @Override
            public void onProductChanged(int productId) {
                // 获取连接的产品类型
                ProductType productType = getProductType();

                if (sdkInitListener != null) {
                    sdkInitListener.onDeviceConnected(productType);
                }
            }

            @Override
            public void onDatabaseDownloadProgress(long current, long total) {
                Log.d(TAG, "数据库下载进度: " + current + "/" + total +
                        " (" + (total > 0 ? (current * 100 / total) : 0) + "%)");

                if (sdkInitListener != null) {
                    sdkInitListener.onDatabaseDownloadProgress(current, total);
                }
            }
        };

        // 设备状态变化监听器
        deviceStatusChangeListener = new DJIDeviceStatusChangeListener() {
            @Override
            public void onDeviceStatusUpdate(DJIDeviceStatus from, DJIDeviceStatus to) {
                Log.d(TAG, "设备状态更新: " +
                        (from != null ? from.name() : "未知") +
                        " -> " +
                        (to != null ? to.name() : "未知"));

                // 检查是否为连接状态变化
                boolean wasConnected = from != null && from.statusCode() == "OK";
                boolean isConnected = to != null && to.statusCode() == "OK";

                if (wasConnected && !isConnected) {
                    // 设备断开连接
                    Log.d(TAG, "设备已断开连接");
                    if (sdkInitListener != null) {
                        sdkInitListener.onDeviceDisconnected();
                    }
                } else if (!wasConnected && isConnected) {
                    // 设备连接
                    Log.d(TAG, "设备已连接");
                    ProductType productType = getProductType();

                    if (sdkInitListener != null) {
                        sdkInitListener.onDeviceConnected(productType);
                    }
                }

                // 通知状态更新
                if (sdkInitListener != null) {
                    sdkInitListener.onDeviceStatusUpdated(from, to);
                }
            }
        };
    }

    /**
     * 注册应用
     */
    public void registerApp() {
        if (!isSDKInitialized) {
            Log.e(TAG, "SDK未初始化，无法注册");
            return;
        }

        try {
            SDKManager.getInstance().registerApp();
            Log.d(TAG, "应用注册请求已发送");
        } catch (Exception e) {
            Log.e(TAG, "应用注册异常: " + e.getMessage());
        }
    }

    /**
     * 获取当前产品类型
     */
    public ProductType getProductType() {
        try {
            // 使用 ProductKey 获取产品类型
            return KeyManager.getInstance().getValue(KeyTools.createKey(ProductKey.KeyProductType));
        } catch (Exception e) {
            Log.e(TAG, "获取产品类型失败: " + e.getMessage());
            return null;
        }
    }

    /**
     * 检查是否有设备连接
     */
    public boolean isDeviceConnected() {
        try {
            // 使用 ProductKey 检查设备连接状态
            Boolean isConnected = KeyManager.getInstance().getValue(KeyTools.createKey(ProductKey.KeyConnection));
            return isConnected != null && isConnected;
        } catch (Exception e) {
            Log.e(TAG, "检查设备连接状态失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 获取固件版本
     */
    public String getFirmwareVersion() {
        try {
            // 使用 ProductKey 获取固件版本
            return KeyManager.getInstance().getValue(KeyTools.createKey(ProductKey.KeyFirmwareVersion));
        } catch (Exception e) {
            Log.e(TAG, "获取固件版本失败: " + e.getMessage());
            return "未知";
        }
    }

    /**
     * 获取序列号
     */
    public String getSerialNumber() {
        try {
            // 使用 ProductKey 获取序列号
            return KeyManager.getInstance().getValue(KeyTools.createKey(ProductKey.KeySerialNumber));
        } catch (Exception e) {
            Log.e(TAG, "获取序列号失败: " + e.getMessage());
            return "未知";
        }
    }

    /**
     * 检查 SDK 是否已初始化
     */
    public boolean isSDKInitialized() {
        return isSDKInitialized;
    }

    /**
     * 检查 SDK 是否已注册
     */
    public boolean isSDKRegistered() {
        return isSDKRegistered;
    }

    /**
     * 获取网络管理器
     */
    public DJINetworkManager getNetworkManager() {
        return DJINetworkManager.getInstance();
    }

    /**
     * 设置 SDK 初始化监听器
     */
    public void setSDKInitListener(SDKInitListener listener) {
        this.sdkInitListener = listener;
    }

    /**
     * 获取 MSDK 包的类型
     */
    public PackageProductCategory getPackageProductCategory() {
        try {
            return SDKManager.getInstance().getProductCategory();
        } catch (Exception e) {
            Log.e(TAG, "获取包产品类别失败: " + e.getMessage());
            return PackageProductCategory.UNKNOWN;
        }
    }

    @Override
    public void onTerminate() {
        super.onTerminate();

        // 销毁 SDK
        try {
            SDKManager.getInstance().destroy();
            Log.d(TAG, "SDK已销毁");
        } catch (Exception e) {
            Log.e(TAG, "SDK销毁异常: " + e.getMessage());
        }
    }

    private void setupCompassHeadingListeners() {
        addLog("开始初始化磁罗盘方向监听...");
        try {
            KeyManager.getInstance().listen(
                    KeyTools.createKey(FlightControllerKey.KeyCompassHeading),
                    this,
                    new CommonCallbacks.KeyListener<Double>() {
                        @Override
                        public void onValueChange(Double oldValue, Double newValue) {
                            if (newValue != null) {
                                String msg = "磁罗盘方向: " + newValue + "°";
                                Log.d(TAG, msg);
                                addLog(msg);
                            }
                        }
                    });
        } catch (Exception e) {
            addLog("初始化磁罗盘方向监听错误: " + e.getMessage());
            Log.e(TAG, "初始化磁罗盘方向监听错误: ", e);
        }
    }

    private void getAttitude() {
        try {
            KeyManager.getInstance().listen(KeyTools.createKey(FlightControllerKey.KeyAircraftAttitude), this, new CommonCallbacks.KeyListener<Attitude>() {
                @Override
                public void onValueChange(Attitude oldValue, Attitude newValue) {
                    if (newValue != null) {
                        String locationLog = "飞行器姿态 - 方位: " + newValue.getYaw() +
                                ", 俯仰: " + newValue.getPitch() +
                                ", 滚转: " + newValue.getRoll() + " m";
                        Log.d(TAG, locationLog);
                    }
                }
            });
        } catch (Exception e) {
            addLog("设置飞行器姿态监听失败: " + e.getMessage());
            Log.e(TAG, "setupAircraftStateListeners (Attitude) failed: ", e);
        }

    }

    private void getVelocity() {
        KeyManager.getInstance().listen(KeyTools.createKey(FlightControllerKey.KeyAircraftVelocity), this, new CommonCallbacks.KeyListener<Velocity3D>() {
            @Override
            public void onValueChange(Velocity3D oldValue, Velocity3D newValue) {
                if (newValue != null) {

                    String locationLog = "飞行器姿态 - 速度x: " + newValue.getX() +
                            ", 速度y: " + newValue.getY() +
                            ", 速度z: " + newValue.getZ() + " m";
                    Log.d(TAG, locationLog);
                }
            }
        });
    }

    private void getPower() {
        KeyManager.getInstance().listen(KeyTools.createKey(BatteryKey.KeyChargeRemainingInPercent), this, new CommonCallbacks.KeyListener<Integer>() {
            @Override
            public void onValueChange(@Nullable Integer oldValue, @Nullable Integer newValue) {
            }
        });
    }
    private void getTemperature() {
        KeyManager.getInstance().listen(KeyTools.createKey(BatteryKey.KeyBatteryTemperature), this, new CommonCallbacks.KeyListener<Double>() {
            @Override
            public void onValueChange(@Nullable Double oldValue, @Nullable Double newValue) {
            }
        });
    }
}
